let extractedData = null;
const API_URL = 'http://xhshot.91jmls.com';

// 更新状态显示
function updateStatus(message, type = '') {
  const statusEl = document.getElementById('status');
  statusEl.textContent = message;
  statusEl.className = type;
}

// 更新按钮状态
function updateButtons(enabled) {
  document.getElementById('copyBtn').disabled = !enabled;
  document.getElementById('sendBtn').disabled = !enabled;
  document.getElementById('extractCoverBtn').disabled = !enabled;
}

// 提取按钮点击事件
document.getElementById('extractBtn').addEventListener('click', async () => {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  
  if (!tab.url.includes('xiaohongshu.com')) {
    updateStatus('请在小红书文章页面使用此扩展', 'error');
    updateButtons(false);
    return;
  }

  updateStatus('正在提取数据...', 'loading');
  updateButtons(false);

  chrome.tabs.sendMessage(tab.id, { action: "extract" }, (response) => {
    if (chrome.runtime.lastError) {
      updateStatus('提取失败，请刷新页面重试', 'error');
      updateButtons(false);
      return;
    }

    extractedData = response;
    updateStatus('提取成功！', 'success');
    updateButtons(true);
  });
});

// 提取封面按钮点击事件
document.getElementById('extractCoverBtn').addEventListener('click', async () => {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  
  if (!tab.url.includes('xiaohongshu.com')) {
    updateStatus('请在小红书文章页面使用此扩展', 'error');
    updateButtons(false);
    return;
  }

  updateStatus('正在提取封面...', 'loading');
  updateButtons(false);

  chrome.tabs.sendMessage(tab.id, { action: "extractCover" }, async (response) => {
    if (chrome.runtime.lastError) {
      updateStatus('提取失败，请刷新页面重试', 'error');
      updateButtons(false);
      return;
    }

    if (response.cover) {
      try {
        await navigator.clipboard.writeText(response.cover);
        updateStatus('封面链接已复制到剪贴板！', 'success');
      } catch (err) {
        updateStatus('封面链接复制失败，请手动复制', 'error');
      }
      extractedData = { cover: response.cover };
    } else {
      updateStatus('未找到封面图片', 'error');
    }
    updateButtons(true);
  });
});

// 复制按钮点击事件
document.getElementById('copyBtn').addEventListener('click', async () => {
  if (!extractedData) {
    updateStatus('请先提取文章数据', 'error');
    return;
  }

  const apiData = {
    title: extractedData.title,
    content: extractedData.content,
    url: extractedData.url,
    keywords: extractedData.keywords,
    cover: extractedData.cover,
    collect: extractedData.collect,
    comment: extractedData.comment,
    like: extractedData.like,
    date: extractedData.date,
    is_hot: true,
    hook: extractedData.keywords ? extractedData.keywords.split(',')[0] : '',
    has_volume: false
  };

  try {
    await navigator.clipboard.writeText(JSON.stringify(apiData, null, 2));
    updateStatus('数据已复制到剪贴板！', 'success');
  } catch (err) {
    updateStatus('复制失败：' + err.message, 'error');
  }
});

// 发送按钮点击事件
document.getElementById('sendBtn').addEventListener('click', async () => {
  if (!extractedData) {
    updateStatus('请先提取文章数据', 'error');
    return;
  }

  const apiData = {
    title: extractedData.title,
    content: extractedData.content,
    url: extractedData.url,
    keywords: extractedData.keywords,
    cover: extractedData.cover,
    collect: extractedData.collect,
    comment: extractedData.comment,
    like: extractedData.like,
    date: extractedData.date,
    is_hot: true,
    hook: extractedData.keywords ? extractedData.keywords.split(',')[0] : '',
    has_volume: false
  };

  try {
    updateStatus('正在发送数据...', 'loading');
    updateButtons(false);

    const response = await fetch(`${API_URL}/api/articles/create`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(apiData)
    });

    const result = await response.json();

    if (response.ok) {
      updateStatus('文章保存成功！', 'success');
    } else {
      throw new Error(result.error || '保存失败');
    }
  } catch (err) {
    updateStatus('保存失败：' + err.message, 'error');
  } finally {
    updateButtons(true);
  }
});
